package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        Page<User> page = new Page<>(currentPage, pageSize);
        Page<User> userPage = userService.page(page);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        com.itheima.pojo.Page page1 = new com.itheima.pojo.Page();
        page1.setRows(records);
        page1.setTotalCount(total);

        Result result = new Result(20041, page1);
        return result;
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        boolean save = userService.save(user);
        Result result = new Result();
        if (save){
            result.setCode(20011);
            result.setMsg("添加成功");
        }else {
            result.setCode(20010);
            result.setMsg("添加失败");
        }
        return result;
    }

    /**
     * 根据用户id删除用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean removeById = userService.removeById(id);
        Result result = new Result();
        if (removeById){
            result.setCode(20021);
            result.setMsg("删除成功");
        }else {
            result.setCode(20020);
            result.setMsg("删除失败");
        }
        return result;
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getId,user.getId());
        boolean update = userService.update(user, qw);
        Result result = new Result();
        if (update){
            result.setCode(20031);
            result.setMsg("更新成功");
        }else {
            result.setCode(20030);
            result.setMsg("更新失败");
        }
        return result;
    }

}
